package cn.cmkj.auction.ui;

import android.content.Intent;
import android.graphics.Paint;
import android.graphics.drawable.Drawable;
import android.net.Uri;
import android.os.Bundle;
import android.support.v4.widget.SwipeRefreshLayout;
import android.text.TextUtils;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.ImageButton;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.jude.rollviewpager.RollPagerView;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.http.HttpMethod;
import org.xutils.http.RequestParams;
import org.xutils.view.annotation.ContentView;
import org.xutils.view.annotation.ViewInject;
import org.xutils.x;

import java.util.ArrayList;
import java.util.List;

import cn.cmkj.auction.R;
import cn.cmkj.auction.adapter.ShuhuaImagePagerAdapter;
import cn.cmkj.auction.app.BaseActivity;
import cn.cmkj.auction.app.Urls;
import cn.cmkj.auction.data.db.User;
import cn.cmkj.auction.data.http.Shuhua;
import cn.cmkj.auction.data.http.ShuhuaImage;
import cn.cmkj.auction.data.http.ShuhuaOrder;
import cn.cmkj.auction.data.http.ShuhuaProps;
import cn.cmkj.auction.utils.DisplayUtil;
import cn.cmkj.auction.utils.HttpCallback;
import cn.cmkj.auction.utils.Utils;
import cn.cmkj.auction.widget.MyScrollView;

/**
 * Created by cunguoyao on 2017/9/20.
 */
@ContentView(R.layout.activity_shuhua_detail)
public class ShuhuaDetailActivity extends BaseActivity implements MyScrollView.ScrollViewListener,SwipeRefreshLayout.OnRefreshListener, View.OnClickListener {

    @ViewInject(R.id.common_title)
    private RelativeLayout titleLayout;
    @ViewInject(R.id.title_back)
    private ImageButton titleBack;
    @ViewInject(R.id.title_text)
    private TextView titleText;
    @ViewInject(R.id.swipeRefreshLayout)
    private SwipeRefreshLayout swipeRefreshLayout;
    @ViewInject(R.id.scrollView)
    private MyScrollView scrollView;
    @ViewInject(R.id.roll_view_pager)
    private RollPagerView rollPagerView;
    private int height;

    @ViewInject(R.id.shu_name)
    private TextView shuNameText;
    @ViewInject(R.id.shu_sale_price)
    private TextView shuSalePriceText;
    @ViewInject(R.id.shu_market_price)
    private TextView shuMarketPrice;
    @ViewInject(R.id.shu_read_num)
    private TextView shuReadNumText;
    @ViewInject(R.id.shu_props)
    private LinearLayout propsLayout;
    @ViewInject(R.id.shu_brief)
    private WebView shuBriefText;
    @ViewInject(R.id.ib_comment)
    private ImageButton ibComment;
    @ViewInject(R.id.ib_call)
    private ImageButton ibCall;
    @ViewInject(R.id.ib_fav)
    private ImageButton ibFav;
    @ViewInject(R.id.ib_cart)
    private ImageButton ibCart;
    @ViewInject(R.id.btn_buy)
    private Button goBuy;

    private Shuhua shuhua;
    private long shuhuaId;
    private List<ShuhuaImage> shuhuaImages;
    private ShuhuaImagePagerAdapter imagePagerAdapter;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        x.view().inject(this);
        shuhua = (Shuhua)getIntent().getSerializableExtra("shuhua");
        shuhuaId = getIntent().getLongExtra("shuhua_id", 0);
        if(shuhua == null && shuhuaId == 0) {
            finish();
            return;
        }
        if(shuhua != null && shuhua.getId() == 0) {
            finish();
            return;
        }
        shuhuaImages = new ArrayList<>();
        if(shuhua != null) {
            //titleText.setText(shuhua.getName());
            titleText.setText("作品详情");
            titleText.setSelected(true);
            List<ShuhuaImage> images = new ArrayList<>();
            ShuhuaImage image = new ShuhuaImage();
            image.l_url = shuhua.getDefaultImage().l_url;
            image.m_url = shuhua.getDefaultImage().m_url;
            image.s_url = shuhua.getDefaultImage().s_url;
            images.add(image);
            shuhuaImages.addAll(images);
        }
        imagePagerAdapter = new ShuhuaImagePagerAdapter(this, shuhuaImages);
        rollPagerView.setAdapter(imagePagerAdapter);
        ViewGroup.LayoutParams layoutParams = rollPagerView.getLayoutParams();
        layoutParams.height = Utils.getScreenWidth(this) * 9 / 16;
        layoutParams.width = Utils.getScreenWidth(this);
        rollPagerView.setLayoutParams(layoutParams);
        //获取顶部图片高度后，设置滚动监听
        ViewTreeObserver vto = rollPagerView.getViewTreeObserver();
        vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
            @Override
            public void onGlobalLayout() {
                rollPagerView.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                height = rollPagerView.getHeight()/4;
                rollPagerView.getWidth();
                scrollView.setScrollViewListener(ShuhuaDetailActivity.this);
            }
        });
        int fontSize = (int) getResources().getDimension(R.dimen.dp_12);
        WebSettings webSettings = shuBriefText.getSettings();
        webSettings.setDefaultFontSize(fontSize);
        webSettings.setUseWideViewPort(true); //将图片调整到适合webview的大小
        webSettings.setLoadWithOverviewMode(true); // 缩放至屏幕的大小
        titleBack.setOnClickListener(this);
        ibCall.setOnClickListener(this);
        ibFav.setOnClickListener(this);
        ibCart.setOnClickListener(this);
        goBuy.setOnClickListener(this);
        //为SwipeRefreshLayout设置监听事件
        swipeRefreshLayout.setOnRefreshListener(this);
        swipeRefreshLayout.setEnabled(true);
        //进入页面自动刷新
        swipeRefreshLayout.post(new Runnable() {
            @Override
            public void run() {
                swipeRefreshLayout.setRefreshing(true);
                fetchData();
                fetchGoodsContextInfo();
            }
        });
    }

    @Override
    public void onRefresh() {
        fetchData();
        fetchGoodsContextInfo();
    }

    private void fetchData() {
        RequestParams params = new RequestParams(Urls.api);
        params.addParameter("method", Urls.goodsDetail);
        if(shuhua != null) {
            params.addParameter("goods_id", shuhua.getId());
        }else {
            params.addParameter("goods_id", shuhuaId);
        }
        User user = getAccount();
        if(user != null) {
            params.addParameter("accesstoken", user.getToken());
            params.addParameter("member_id", user.getId());
        }
        x.http().request(HttpMethod.POST, params, new HttpCallback(this) {
            @Override
            public void success(String s) {
                swipeRefreshLayout.setRefreshing(false);
                JSONObject jsonStr = null;
                try {
                    jsonStr = new JSONObject(s);
                    JSONObject json = jsonStr.optJSONObject("data");
                    JSONObject jsonObject = json.optJSONObject("page_product_basic");
                    shuhua = Shuhua.parseFromJsonForDetail(jsonObject);
                    if(shuhua != null) {
                        shuhua.setFav(json.optBoolean("is_fav", false));
                        shuhua.setCart(json.optBoolean("is_cart", false));
                    }
                    fillData();
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void error(Throwable ex, String msg, boolean isOnCallback) {
                swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void cancel(CancelledException e) {
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    private void fetchGoodsContextInfo() {
        RequestParams params = new RequestParams(Urls.api);
        params.addParameter("method", Urls.goodsIntro);
        if(shuhua != null) {
            params.addParameter("goods_id", shuhua.getId());
        }else {
            params.addParameter("goods_id", shuhuaId);
        }
        x.http().request(HttpMethod.POST, params, new HttpCallback(this) {
            @Override
            public void success(String s) {
                swipeRefreshLayout.setRefreshing(false);
                JSONObject jsonStr = null;
                try {
                    jsonStr = new JSONObject(s);
                    JSONObject json = jsonStr.optJSONObject("data");
                    String webData = json.optString("goods_context");
                    shuBriefText.loadData(webData, "text/html; charset=UTF-8", null);
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void error(Throwable ex, String msg, boolean isOnCallback) {
                swipeRefreshLayout.setRefreshing(false);
            }

            @Override
            public void cancel(CancelledException e) {
                swipeRefreshLayout.setRefreshing(false);
            }
        });
    }

    private void fillData() {
        //titleText.setText(shuhua.getName());
        titleText.setText("作品详情");
        titleText.setSelected(true);
        shuhuaImages.clear();
        shuhuaImages.addAll(shuhua.getImages());
        imagePagerAdapter.notifyDataSetChanged();

        shuNameText.setText(shuhua.getName());
        shuSalePriceText.setText("￥" + shuhua.getSalePrice().doubleValue());
        shuMarketPrice.setText("￥" + shuhua.getSalePrice().doubleValue());
        shuMarketPrice.getPaint().setFlags(Paint.STRIKE_THRU_TEXT_FLAG); //中划线
        shuReadNumText.setText("浏览量:" + shuhua.getReadNum());

        LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
        Drawable drawable= getResources().getDrawable(R.drawable.shu_desc_point);
        drawable.setBounds(0, 0, drawable.getMinimumWidth(), drawable.getMinimumHeight());

        if(shuhua.getProps() != null && shuhua.getProps().size() > 0) {
            propsLayout.removeAllViews();
            for(ShuhuaProps prop : shuhua.getProps()) {
                TextView mTextView = new TextView(this);
                mTextView.setCompoundDrawables(drawable,null,null,null);//设置TextView的drawableleft
                mTextView.setCompoundDrawablePadding(DisplayUtil.dip2px(this, 10));//设置图片和text之间的间距
                mTextView.setPadding(DisplayUtil.dip2px(this, 15), DisplayUtil.dip2px(this, 10), 0, DisplayUtil.dip2px(this, 0));
                mTextView.setTextSize(16);
                mTextView.setTextColor(getResources().getColor(R.color.b_80));
                mTextView.setText(prop.name + "：" + prop.value);
                propsLayout.addView(mTextView, layoutParams);
            }
        }
        TextView mTextView1 = new TextView(this);
        mTextView1.setCompoundDrawables(drawable,null,null,null);//设置TextView的drawableleft
        mTextView1.setCompoundDrawablePadding(DisplayUtil.dip2px(this, 10));//设置图片和text之间的间距
        mTextView1.setPadding(DisplayUtil.dip2px(this, 15), DisplayUtil.dip2px(this, 10), 0, DisplayUtil.dip2px(this, 0));
        mTextView1.setTextSize(16);
        mTextView1.setTextColor(getResources().getColor(R.color.b_80));
        mTextView1.setText("作品编号" + "：" + shuhua.getBn());
        propsLayout.addView(mTextView1, 0, layoutParams);
        TextView mTextView2 = new TextView(this);
        mTextView2.setCompoundDrawables(drawable,null,null,null);//设置TextView的drawableleft
        mTextView2.setCompoundDrawablePadding(DisplayUtil.dip2px(this, 10));//设置图片和text之间的间距
        mTextView2.setPadding(DisplayUtil.dip2px(this, 15), DisplayUtil.dip2px(this, 10), 0, DisplayUtil.dip2px(this, 0));
        mTextView2.setTextSize(16);
        mTextView2.setTextColor(getResources().getColor(R.color.b_80));
        mTextView2.setText("分类" + "：" + shuhua.getTypeName());
        propsLayout.addView(mTextView2, layoutParams);
        if(shuhua.isFav()) {
            ibFav.setImageResource(R.drawable.icon_fav_ed);
        }else {
            ibFav.setImageResource(R.drawable.icon_fav);
        }
        if(shuhua.isCart()) {
            ibCart.setImageResource(R.drawable.icon_cart_ed);
        }else {
            ibCart.setImageResource(R.drawable.icon_cart);
        }
    }

    @Override
    public void onScrollChanged(MyScrollView scrollView, int x, int y, int oldx, int oldy) {
        if(y<=height && y>=0){
            //titleBack.setImageResource(R.drawable.icon_back);
            //titleBack.setBackgroundResource(R.drawable.ic_back_bg);
            //标题栏 不透明
            titleLayout.setBackgroundColor(getResources().getColor(R.color.title_color));
            //setStatusBar(false, R.color.white);
        }
        else if(y > height){
            float scale =(float) y /height;
            float alpha =  (255 * scale);
            //titleBack.setImageResource(R.drawable.ic_back_poi_bg);
            //titleBack.setBackgroundResource(R.drawable.ic_back_bg);
            //titleLayout.setBackgroundColor(Color.argb((int) alpha, 0xff, 0xff, 0xff));
            //标题栏 透明
            titleLayout.setBackgroundColor(getResources().getColor(R.color.title_color));
            //setStatusBar(false, R.color.white);
        }
    }

    private void call() {
        Intent intent = new Intent(Intent.ACTION_DIAL, Uri.parse("tel:" + Urls.TEL_KF));
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivity(intent);
    }

    private void addFav() {
        RequestParams params = new RequestParams(Urls.api);
        params.addParameter("method", Urls.addFav);
        params.addParameter("goods_id", shuhua.getId());
        User user = getAccount();
        if(user == null) {
            showLoginDialog(this);
        }else {
            showLoading();
            params.addParameter("accesstoken", user.getToken());
            params.addParameter("member_id", user.getId());
            x.http().request(HttpMethod.POST, params, new HttpCallback(this) {
                @Override
                public void success(String s) {
                    dismissLoading();
                    JSONObject jsonStr = null;
                    try {
                        jsonStr = new JSONObject(s);
                        JSONObject json = jsonStr.optJSONObject("data");
                        boolean success = json.optBoolean("status");
                        if(success) {
                            shuhua.setFav(true);
                            ibFav.setImageResource(R.drawable.icon_fav_ed);
                        }
                        String toast = json.optString("message");
                        if(!TextUtils.isEmpty(toast)) {
                            Toast.makeText(ShuhuaDetailActivity.this, toast, Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void error(Throwable ex, String msg, boolean isOnCallback) {
                    dismissLoading();
                    if(!TextUtils.isEmpty(msg)) {
                        Toast.makeText(ShuhuaDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void cancel(CancelledException e) {
                    dismissLoading();
                }

                @Override
                public void finished() {
                    dismissLoading();
                }
            });
        }
    }

    private void delFav() {
        RequestParams params = new RequestParams(Urls.api);
        params.addParameter("method", Urls.delFav);
        params.addParameter("goods_id", shuhua.getId());
        User user = getAccount();
        if(user == null) {
            showLoginDialog(this);
        }else {
            showLoading();
            params.addParameter("accesstoken", user.getToken());
            params.addParameter("member_id", user.getId());
            x.http().request(HttpMethod.POST, params, new HttpCallback(this) {
                @Override
                public void success(String s) {
                    dismissLoading();
                    JSONObject jsonStr = null;
                    try {
                        jsonStr = new JSONObject(s);
                        JSONObject json = jsonStr.optJSONObject("data");
                        boolean success = json.optBoolean("status");
                        if(success) {
                            shuhua.setFav(false);
                            ibFav.setImageResource(R.drawable.icon_fav);
                        }
                        String toast = json.optString("message");
                        if(!TextUtils.isEmpty(toast)) {
                            Toast.makeText(ShuhuaDetailActivity.this, toast, Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void error(Throwable ex, String msg, boolean isOnCallback) {
                    dismissLoading();
                    if(!TextUtils.isEmpty(msg)) {
                        Toast.makeText(ShuhuaDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void cancel(CancelledException e) {
                    dismissLoading();
                }

                @Override
                public void finished() {
                    dismissLoading();
                }
            });
        }
    }

    private void addCart() {
        RequestParams params = new RequestParams(Urls.api);
        params.addParameter("method", Urls.addCart);
        params.addParameter("type", "goods");
        params.addParameter("num", "1");
        params.addParameter("goods_id", shuhua.getId());
        params.addParameter("product_id", shuhua.getProductId());
        User user = getAccount();
        if(user == null) {
            showLoginDialog(this);
        }else {
            showLoading();
            params.addParameter("accesstoken", user.getToken());
            params.addParameter("member_id", user.getId());
            x.http().request(HttpMethod.POST, params, new HttpCallback(this) {
                @Override
                public void success(String s) {
                    dismissLoading();
                    JSONObject jsonStr = null;
                    try {
                        jsonStr = new JSONObject(s);
                        JSONObject json = jsonStr.optJSONObject("data");
                        boolean success = json.optBoolean("status");
                        if(success) {
                            shuhua.setCart(true);
                            ibCart.setImageResource(R.drawable.icon_cart_ed);
                        }
                        String toast = json.optString("message");
                        if(!TextUtils.isEmpty(toast)) {
                            Toast.makeText(ShuhuaDetailActivity.this, toast, Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void error(Throwable ex, String msg, boolean isOnCallback) {
                    dismissLoading();
                    if(!TextUtils.isEmpty(msg)) {
                        Toast.makeText(ShuhuaDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void cancel(CancelledException e) {
                    dismissLoading();
                }

                @Override
                public void finished() {
                    dismissLoading();
                }
            });
        }
    }

    private void removeCart() {
        RequestParams params = new RequestParams(Urls.api);
        params.addParameter("method", Urls.removeCart);
        params.addParameter("type", "goods");
        params.addParameter("remove_all", "false");
        params.addParameter("goods_id", shuhua.getId());
        params.addParameter("product_id", shuhua.getProductId());
        User user = getAccount();
        if(user == null) {
            showLoginDialog(this);
        }else {
            showLoading();
            params.addParameter("accesstoken", user.getToken());
            params.addParameter("member_id", user.getId());
            x.http().request(HttpMethod.POST, params, new HttpCallback(this) {
                @Override
                public void success(String s) {
                    dismissLoading();
                    JSONObject jsonStr = null;
                    try {
                        jsonStr = new JSONObject(s);
                        JSONObject json = jsonStr.optJSONObject("data");
                        boolean success = json.optBoolean("status");
                        if(success) {
                            shuhua.setCart(false);
                            ibCart.setImageResource(R.drawable.icon_cart);
                        }
                        String toast = json.optString("message");
                        if(!TextUtils.isEmpty(toast)) {
                            Toast.makeText(ShuhuaDetailActivity.this, toast, Toast.LENGTH_SHORT).show();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void error(Throwable ex, String msg, boolean isOnCallback) {
                    dismissLoading();
                    if(!TextUtils.isEmpty(msg)) {
                        Toast.makeText(ShuhuaDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void cancel(CancelledException e) {
                    dismissLoading();
                }

                @Override
                public void finished() {
                    dismissLoading();
                }
            });
        }
    }

    private void orderPre() {
        RequestParams params = new RequestParams(Urls.api);
        params.addParameter("method", Urls.orderPre);
        params.addParameter("isfastbuy", "true");
        params.addParameter("buy_goods", "[{\"goods_id\":\"" + shuhua.getId() + "\", \"product_id\":\"" + shuhua.getProductId() + "\"}]");
        User user = getAccount();
        if(user == null) {
            showLoginDialog(this);
        }else {
            showLoading();
            params.addParameter("accesstoken", user.getToken());
            params.addParameter("member_id", user.getId());
            x.http().request(HttpMethod.POST, params, new HttpCallback(this) {
                @Override
                public void success(String s) {
                    dismissLoading();
                    JSONObject jsonStr = null;
                    try {
                        jsonStr = new JSONObject(s);
                        JSONObject json = jsonStr.optJSONObject("data");
                        ShuhuaOrder order = ShuhuaOrder.parseFromJsonByPreOrder(json);
                        if(order != null) {
                            Intent intent = new Intent(ShuhuaDetailActivity.this, OrderDetailActivity.class);
                            intent.putExtra(OrderDetailActivity.FROM, OrderDetailActivity.FROM_PRE_ORDER);
                            intent.putExtra("order", order);
                            startActivityForResult(intent, 1);
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

                @Override
                public void error(Throwable ex, String msg, boolean isOnCallback) {
                    dismissLoading();
                    if(!TextUtils.isEmpty(msg)) {
                        Toast.makeText(ShuhuaDetailActivity.this, msg, Toast.LENGTH_SHORT).show();
                    }
                }

                @Override
                public void cancel(CancelledException e) {
                    dismissLoading();
                }

                @Override
                public void finished() {
                    dismissLoading();
                }
            });

        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == 1) {
                finish();
            }
        }
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.title_back:
                finish();
                break;
            case R.id.ib_call:
                call();
                break;
            case R.id.ib_fav:
                if(shuhua.isFav()) {
                    delFav();
                }else {
                    addFav();
                }
                break;
            case R.id.ib_cart:
                if(shuhua.isCart()) {
                    removeCart();
                }else {
                    addCart();
                }
                break;
            case R.id.btn_buy:
                orderPre();
                break;
        }
    }
}
